package main

import (
	"context"
	"flag"
	"fmt"
	"gpt-api/framework/config"
	"gpt-api/framework/log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	_ "gpt-api/docs"

	"github.com/pkg/errors"
)

func main() {
	var addr, cfg string
	flag.StringVar(&addr, "addr", ":8892", "server listen and serve address, like 127.0.0.1:8888 or :8080")
	// flag.StringVar(&cfg, "config", "/Users/jean/works/yq/config/api.yaml", "the config file path")

	configFile := "D:/work/yq/config/api.yaml"
	// 生产环境可以通过设置环境变量来改变配置文件路径
	if configEnv := os.Getenv("YI_QIAO_DIR"); configEnv != "" {
		configFile = configEnv + "/config/api.yaml"
	}
	fmt.Println("configFile:", configFile)
	flag.StringVar(&cfg, "config", configFile, "the config file path")
	flag.Parse()

	if err := config.ReadYamlConfigs(cfg); err != nil {
		log.Fatal("read config", log.Errors("config", err))
	}
	if err := startServer(addr); err != nil {
		log.Fatal("start server", log.Errors("start", err))
	}
}

func startServer(addr string) error {
	router, err := NewRouter()
	if err != nil {
		return errors.Wrapf(err, "Create routers")
	}
	srv := &http.Server{
		Addr:         addr,
		Handler:      router,
		ReadTimeout:  60 * time.Second,
		WriteTimeout: 60 * time.Second,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatal("ListenAndServe", log.Errors("listen", err))
		}
	}()

	log.Info("Start Server Success")
	// Wait for interrupt signal to gracefully shut down the server with
	// a timeout of 10 seconds.
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
	<-quit
	log.Info("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)

	defer cancel()

	ctx1, cancel := context.WithDeadline(ctx, time.Now().Add(30*time.Second))
	defer cancel()

	if err := srv.Shutdown(ctx1); err != nil {
		return errors.Wrap(err, "Server Shutdown")
	}

	return nil
}
